package com.lyf.language.learn.atsgg.io.stream;

import org.junit.Test;

import java.io.*;

/**
 * @AUTHOR LYF
 * @DATE 2022/6/3
 * @VERSION 1.0
 * @DESC
 * 对象流的使用（处理流）
 * 理解序列化机制（基本类型和自定义
 */
public class ObjectStreamDemo {
    String filePath = "E:\\JavaProjects\\LearnProjects\\learn-practice\\java-base\\src\\main\\java\\com\\lyf\\language\\learn\\atsgg\\io\\stream\\hello.dat";
    // Junit4--单元测试

    /**
     * 序列化是输出到源，二进制，方便网络等传输，无法直接查看
     */
    @Test
    public void testObjectOutPutStream(){
        File file = new File(filePath);
        ObjectOutputStream oos = null;
        try {
                // 处理流 需要包裹节点流
                oos =   new ObjectOutputStream(new FileOutputStream(file));
                oos.writeObject("I love Y");//String 对象--
                oos.flush();
                oos = null;//测试断言的理解
        } catch (IOException e) {
                e.printStackTrace();
        }finally {
            try {
                assert oos != null;// assert？
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void testObjectInputStream(){
        File file = new File(filePath);
        ObjectInputStream ois = null;
        try {
            // 处理流 需要包裹节点流
            ois =   new ObjectInputStream(new FileInputStream(file));

            try {
                Object o = ois.readObject();
                if(o instanceof String){
                    System.out.println(o);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                assert ois != null;// assert？
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
